package com.xiaoshuidi.cloud.module.member.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoshuidi.cloud.module.member.mapper.coupon.MemberCouponApartmentMapper;
import com.xiaoshuidi.cloud.module.member.pojo.coupon.MemberCouponApartment;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Repository
@RequiredArgsConstructor
public class MemberCouponApartmentRepository extends ServiceImpl<MemberCouponApartmentMapper, MemberCouponApartment> {
    private final MemberCouponApartmentMapper mapper;

    public void updateApartment(Long id, List<Long> apartmentIds) {
        //简单过滤
        List<MemberCouponApartment> apartments = getApartmentsByCouponId(id);
        List<Long> collect = apartments.stream().map(MemberCouponApartment::getApartmentId).collect(Collectors.toList());
        if (!isEqualCollect(apartmentIds, collect)) {
            //门店发生了变化
            deleteByCouponId(id);
            this.insertApartment(id, apartmentIds);
        }
    }

    public List<MemberCouponApartment> getApartmentsByCouponId(Long id) {
        LambdaQueryWrapper<MemberCouponApartment> wrapper = new LambdaQueryWrapper<MemberCouponApartment>().eq(MemberCouponApartment::getCouponId, id);
        List<MemberCouponApartment> apartments = mapper.selectList(wrapper);
        return apartments;
    }

    public void deleteByCouponId(Long id) {
        Map<String, Object> map = new HashMap<>();
        map.put("coupon_id", id);
        mapper.deleteByMap(map);
    }

    public boolean isEqualCollect(List<Long> list, List<Long> list2) {
        boolean flag = false;
        if (list.size() == list2.size()) {
            if (list.containsAll(list2)) {
                flag = true;
            }
        }
        return flag;
    }

    public void insertApartment(Long id, List<Long> apartmentIds) {
        List<MemberCouponApartment> list = new ArrayList<>();
        for (Long apartmentId : apartmentIds) {
            MemberCouponApartment couponApartment = new MemberCouponApartment();
            couponApartment.setCouponId(id);
            couponApartment.setApartmentId(apartmentId);
            list.add(couponApartment);
        }
        this.saveBatch(list);
    }
}
